package com.yunji.news.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yunji.news.common.Result;
import com.yunji.news.dto.AnnualEnrollmentInfoWithSchoolDTO;
import com.yunji.news.entity.AnnualEnrollmentInfo;
import com.yunji.news.entity.School;
import com.yunji.news.service.AnnualEnrollmentInfoService;
import com.yunji.news.service.SchoolService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 年度招生信息管理控制器（管理员接口）
 *
 * @author yunji
 * @since 2025-11-27
 */
@Slf4j
@RestController
@RequestMapping("/admin/annual-enrollment")
@RequiredArgsConstructor
public class AdminAnnualEnrollmentController {

    private final AnnualEnrollmentInfoService annualEnrollmentInfoService;
    private final SchoolService schoolService;

    /**
     * 分页查询年度招生信息
     */
    @GetMapping
    public Result<IPage<AnnualEnrollmentInfoWithSchoolDTO>> getPage(
            @RequestParam(defaultValue = "1") Long current,
            @RequestParam(defaultValue = "20") Long size,
            @RequestParam(required = false) Integer year,
            @RequestParam(required = false) String schoolName,
            @RequestParam(required = false) Integer status) {

        Page<AnnualEnrollmentInfo> page = new Page<>(current, size);
        
        LambdaQueryWrapper<AnnualEnrollmentInfo> wrapper = new LambdaQueryWrapper<AnnualEnrollmentInfo>()
                .eq(year != null, AnnualEnrollmentInfo::getYear, year)
                .eq(status != null, AnnualEnrollmentInfo::getStatus, status)
                .orderByAsc(AnnualEnrollmentInfo::getSortOrder)
                .orderByDesc(AnnualEnrollmentInfo::getCreatedAt);

        IPage<AnnualEnrollmentInfo> enrollmentPage = annualEnrollmentInfoService.page(page, wrapper);
        
        // 获取学校信息
        List<School> allSchools = schoolService.list();
        Map<Long, School> schoolMap = allSchools.stream()
                .collect(Collectors.toMap(School::getId, school -> school));

        // 转换为DTO
        List<AnnualEnrollmentInfoWithSchoolDTO> dtoList = enrollmentPage.getRecords().stream()
                .map(enrollment -> {
                    AnnualEnrollmentInfoWithSchoolDTO dto = new AnnualEnrollmentInfoWithSchoolDTO();
                    BeanUtils.copyProperties(enrollment, dto);
                    
                    School school = schoolMap.get(enrollment.getSchoolId());
                    if (school != null) {
                        dto.setSchoolName(school.getName());
                        dto.setSchoolShortName(school.getShortName());
                        
                        if (StringUtils.hasText(schoolName) && 
                            !school.getName().contains(schoolName)) {
                            return null;
                        }
                    }
                    return dto;
                })
                .filter(dto -> dto != null)
                .collect(Collectors.toList());

        Page<AnnualEnrollmentInfoWithSchoolDTO> resultPage = new Page<>(current, size);
        resultPage.setRecords(dtoList);
        resultPage.setTotal(enrollmentPage.getTotal());
        resultPage.setSize(enrollmentPage.getSize());
        resultPage.setCurrent(enrollmentPage.getCurrent());

        return Result.success(resultPage);
    }

    /**
     * 根据ID获取详情
     */
    @GetMapping("/{id}")
    public Result<AnnualEnrollmentInfo> getById(@PathVariable Long id) {
        AnnualEnrollmentInfo enrollment = annualEnrollmentInfoService.getById(id);
        return Result.success(enrollment);
    }

    /**
     * 创建年度招生信息
     */
    @PostMapping
    public Result<Void> create(@RequestBody AnnualEnrollmentInfo enrollment) {
        log.info("创建年度招生信息: 学校ID={}, 年份={}", enrollment.getSchoolId(), enrollment.getYear());
        
        // 检查是否已存在同一学校同一年份的记录
        LambdaQueryWrapper<AnnualEnrollmentInfo> wrapper = new LambdaQueryWrapper<AnnualEnrollmentInfo>()
                .eq(AnnualEnrollmentInfo::getSchoolId, enrollment.getSchoolId())
                .eq(AnnualEnrollmentInfo::getYear, enrollment.getYear());
        
        if (annualEnrollmentInfoService.count(wrapper) > 0) {
            return Result.error("该学校该年份的招生信息已存在");
        }
        
        annualEnrollmentInfoService.save(enrollment);
        return Result.success();
    }

    /**
     * 更新年度招生信息
     */
    @PutMapping("/{id}")
    public Result<Void> update(@PathVariable Long id, @RequestBody AnnualEnrollmentInfo enrollment) {
        log.info("更新年度招生信息: ID={}, 学校ID={}, 年份={}", id, enrollment.getSchoolId(), enrollment.getYear());
        
        enrollment.setId(id);
        annualEnrollmentInfoService.updateById(enrollment);
        return Result.success();
    }

    /**
     * 删除年度招生信息
     */
    @DeleteMapping("/{id}")
    public Result<Void> delete(@PathVariable Long id) {
        log.info("删除年度招生信息: ID={}", id);
        
        annualEnrollmentInfoService.removeById(id);
        return Result.success();
    }

    /**
     * 批量删除
     */
    @DeleteMapping("/batch")
    public Result<Void> deleteBatch(@RequestBody List<Long> ids) {
        log.info("批量删除年度招生信息: IDs={}", ids);
        
        annualEnrollmentInfoService.removeByIds(ids);
        return Result.success();
    }
}